// @ts-nocheck
var express = require("express");
var router = express.Router();
const multer = require("multer");
const upload = multer();

const path = require("path");
// 获取md5库
const md5 = require(path.resolve(__dirname, "../public/js/md5.js"));

router.post("/", upload.single("file"), async function (req, res) {
	const { hash, key, start, index } = req.body;
	const file = req.file;
	const flag = await analyzeChunk(file, hash);
	// 如果校验通过，则写入
	if (flag) {
		const result = await appendFile(key, file.buffer, +start);
		if (result === "ok") {
			// 写入之后，将对应的标识符改为1
			const fileMap = keyMap.get(key);
			fileMap.hasResolve[index] = 1;
			res.send(
				JSON.stringify({
					code: 200,
					data: "ok",
				})
			);
			// 如果每个分块都已写入，那么就关闭fd
			if (fileMap.hasResolve.every((item) => item === 1)) {
				fileMap.fd.close();
				// 将对应key的map删除
				keyMap.delete(key);
			}
		} else {
			res.send(
				JSON.stringify({
					code: 200,
					data: "fail",
				})
			);
		}
	} else {
		res.send(
			JSON.stringify({
				code: 200,
				data: "fail",
			})
		);
	}
});

// 追加文件
async function appendFile(key, buffer, start) {
	if (!keyMap.has(key)) {
		return "文件尚未准备就绪";
	}
	let fd = keyMap.get(key).fd;
	await fd.writev([buffer], start);
	return "ok";
}

// 解析分块
function analyzeChunk(chunk, chunkHash) {
	// 获取二进制对象
	const blob = chunk.buffer;

	// 函数hash
	const spark = new md5.ArrayBuffer();

	// 获取Promise
	return new Promise((resolve, reject) => {
		spark.append(blob);
		if (spark.end() === chunkHash) {
			resolve(true);
		} else {
			reject(false);
		}
	});
}

module.exports = router;
